package com.atguigu.securitydemo1.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @author Jungle
 * @create 2022-10-07 20:27
 */
@Configuration
public class SecurityAdvanceConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    //注入数据源
    @Autowired
    private DataSource dataSource;
    //配置对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //这句可以自动创建表，这里手动创建过了，就不创建了
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }





    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }





    /**
     * 需要注入这个对象，不然会报错
     */
    @Bean
    public PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 部分页面需要拦截吗，部分不用拦截
     * 可以定义哪些需要认证，哪些不用认证
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //退出 用户注销
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

        //配置没有访问权限跳转的自定义页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin()    //自定义自己编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/success.html").permitAll()  //登录成功之后，跳转路径
                .and().authorizeRequests()
                .antMatchers("/", "/test/hello", "/user/login").permitAll()   //设置哪些路径直接访问，不需要认证
                //当前登录的用户，只有具有admins权限，才可以访问这个路径
                //1.hasAuthority 方法
                //.antMatchers("/test/index").hasAuthority("admins")  //单个授权
                //2.hasAnyAuthority 方法
                //.antMatchers("/test/index").hasAnyAuthority("admins,manager")  //多个授权
                //3.hasRole方法
                .antMatchers("/test/index").hasRole("sale")  //单个角色
                .anyRequest().authenticated()

                //设置自动登录（10天免登录）
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60) //设置有效时长 60s
                .userDetailsService(userDetailsService)
                    //关闭csrf防护
                .and().csrf().disable();
    }
}
